package service

import (
	"context"
	"fmt"
	"ginchat/models"
	untils "ginchat/utils"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"time"
)

/*
https://blog.csdn.net/qq_17525509/article/details/130973891
*/

// 防止跨域站点为找请求
var upGrade = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// SendMsg 消息发送
func SendMsg(c *gin.Context) {
	ws, err := upGrade.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println("ws数据打印", err)
		return
	}
	defer func(ws *websocket.Conn) {
		err = ws.Close()
		if err != nil {
			fmt.Println("错误的ws日志打印")
		}
	}(ws)
	MsgHandler(ws, c)
}

// MsgHandler 消息中间件
func MsgHandler(ws *websocket.Conn, c context.Context) {
	msg, err := untils.Subscribe(c, untils.PublishKey)
	fmt.Println("消息打印", msg)
	if err != nil {
		fmt.Println("错误打印", err)
	}
	tm := time.Now().Format("2006-01-02 15:04:05")
	m := fmt.Sprintf("[ws][%s]:%s", tm, msg)
	err = ws.WriteMessage(1, []byte(m))
	if err != nil {
		fmt.Println("消息异常打印", err)
	}
}

// SendUserMsg 点对点聊天
func SendUserMsg(c *gin.Context) {
	models.Chat(c.Writer, c.Request)
}

func ToChat(c *gin.Context) {
	// 请求参数
	// UserId   int64 `json:"user_id"`
	type ChatReq struct {
		TargetId int64 `json:"target_id"`
	}
	var ChatParams ChatReq
	if err := c.ShouldBindBodyWithJSON(&ChatParams); err != nil {
		fmt.Println("请求参数错误", err)
		return
	}
}
